import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

// Element Plus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// HTTP请求库
import request from './utils/request'

// 图表库
import ECharts from 'vue-echarts'
import { use } from 'echarts/core'
import {
  CanvasRenderer
} from 'echarts/renderers'
import {
  BarChart,
  LineChart,
  PieChart
} from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'

// 时间处理库
import moment from 'moment'

// 注册echarts组件
use([
  CanvasRenderer,
  BarChart,
  LineChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

// 创建应用实例
const app = createApp(App)

// 使用Element Plus
app.use(ElementPlus, {
  size: 'default'
})

// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 注册图表组件
app.component('v-chart', ECharts)

// 全局属性
app.config.globalProperties.$http = request
app.config.globalProperties.$moment = moment

// 全局过滤器（Vue 3中移除了过滤器，改用全局属性）
app.config.globalProperties.$filters = {
  formatDate(value, format = 'YYYY-MM-DD HH:mm:ss') {
    if (!value) return ''
    return moment(value).format(format)
  },
  
  formatAqiLevel(level) {
    const levels = {
      1: { name: '优', color: '#00e400' },
      2: { name: '良', color: '#ffff00' },
      3: { name: '轻度污染', color: '#ff7e00' },
      4: { name: '中度污染', color: '#ff0000' },
      5: { name: '重度污染', color: '#8f3f97' },
      6: { name: '严重污染', color: '#7e0023' }
    }
    return levels[level] || { name: '未知', color: '#999' }
  },
  
  formatStatus(status) {
    const statusMap = {
      0: { name: '待分配', type: 'info' },
      1: { name: '已分配', type: 'warning' },
      2: { name: '已确认', type: 'success' }
    }
    return statusMap[status] || { name: '未知', type: 'info' }
  }
}

// 全局错误处理
app.config.errorHandler = (err, instance, info) => {
  console.error('Vue Error:', err, info)
  // ElementPlus的消息提示需要在组件中使用ElMessage
}

// 使用路由和状态管理
app.use(store)
app.use(router)

// 初始化应用时的设置
store.dispatch('app/loadProvinces')

// 如果有token，验证token有效性
const token = store.getters['user/token']
if (token) {
  store.dispatch('user/validateToken').catch(() => {
    store.dispatch('user/logout')
  })
}

// 挂载应用
app.mount('#app')
